package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gongpingjialoan.R;
import com.gongpingjialoan.adapter.LooperAdapter;
import com.gongpingjialoan.adapter.car.CarlistSelectFilterAdapter;
import com.gongpingjialoan.bean.BannerBean;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.SelectBean;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.widget.MyGridView;
import com.gongpingjialoan.widget.VipBuycarFilterPopupWindow;
import com.gongpingjialoan.widget.VipLimitDialog;
import com.gongpingjialoan.widget.autoviewpagers.ColorPointHintView;
import com.gongpingjialoan.widget.autoviewpagers.RollPagerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2016/6/23.
 */
public class NoIntentFragment extends AnimationFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private BuyCarVipActivity mBuyCarVipActivity;
//    //价格    (单选)
//    private String[] show_prices = {"5万以内", "5-10万", "10-15万", "15-20万", "20-30万", "30-50万", "50万以上", "自定义"};
//    private String[] need_prices = {"0-5", "5-10", "10-15", "15-20", "20-30", "30-50", "50-", ""};

    //用途    (多选)
    private String[] show_function = {"代步", "家用", "商用", "越野"};
    private String[] need_function = {"代步", "家用", "商用", "越野"};

    //用途    (多选)
    private String[] show_intent = {"微型车", "小型车", "中级车", "中高级车", "SUV", "跑车", "豪华车", "商务车"};
    private String[] need_intent = {"mini_car", "small_car,compact_car", "middle_car", "middle_super_car", "suv", "super_car", "luxury_car", "mpv"};


    //购车时间    (多选)
    private String[] show_time = {"1~2周内", "1个月内", "2个月内", "半年内", "先看看"};
    private String[] need_time = {"one_or_two_weeks", "one_month", "two_months", "six_months", "not_set"};

    //其它需求    (多选)
    private String[] show_other = {"七座车", "省油", "提速快", "混合动力", "四驱", "进口车", "有天窗", "自定义"};
    private String[] need_other = {"七座车", "省油", "提速快", "混合动力", "四驱", "进口车", "有天窗", ""};

    private VipBuycarBean mVipBuycarBean;

    private TextView intent_textview;

    private MyGridView functionMyGridView, intentMyGridView, otherMyGridView, timeGridView;
    private CarlistSelectFilterAdapter adapter_time, adapter_function, adapter_intent, adapter_other;
    private List<SelectBean> list_function, list_time, list_intent, list_other;
    private String str_function = "", str_intent = "", str_others = "", str_time = "", str_price = "";

    private String other_msg;

    private Button sureButton;

    private VipLimitDialog mVipLimitDialog;

    private EditText priceEditText;

    private AppCompatEditText mAppCompatEditText;

    private View loginLinearLayout;

    private boolean isPhoneNumRight = false;


    private RollPagerView mRollPagerView;

    private LooperAdapter mLooperAdapter;

    private LinearLayout rollLinearLayout;

    private View view;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        action = "vipBuy";
        isScrollPage = true;
        view = inflater.inflate(R.layout.nointent_layout, container, false);
        mBuyCarVipActivity = (BuyCarVipActivity) getActivity();
        initView();
        return view;
    }


    public void initBanner() {
        BannerBean bannerBean = GPJApplication.getInstance().mBannerBean;
        if (bannerBean != null && "success".equals(bannerBean.getStatus())) {
            List<BannerBean.DataEntity.EvalEntity> dataEntities = bannerBean.getData().getVipbuy();
            if (dataEntities != null && dataEntities.size() > 0) {
                Glide.with(mBuyCarVipActivity).load(dataEntities.get(0).getImg()).into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        int width = getResources().getDisplayMetrics().widthPixels;
                        int height = resource.getIntrinsicHeight() * width / resource.getIntrinsicWidth();
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
                        rollLinearLayout.addView(mRollPagerView, lp);
                    }
                });
                view.findViewById(R.id.vip_zu).setVisibility(View.GONE);
                mRollPagerView.setVisibility(View.VISIBLE);
                mLooperAdapter = new LooperAdapter(mRollPagerView, dataEntities, getActivity(), getFragmentManager(), false);
                mRollPagerView.setAdapter(mLooperAdapter);
            }
        }
    }


    private void initView() {
        intent_textview = (TextView) view.findViewById(R.id.intent_textview);
        mVipBuycarBean = new VipBuycarBean();
        loginLinearLayout = view.findViewById(R.id.loginlayout);

        priceEditText = (EditText) view.findViewById(R.id.price);
        rollLinearLayout = (LinearLayout) view.findViewById(R.id.rollmain);
        mRollPagerView = new RollPagerView(getActivity());
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));
        mRollPagerView.setPlayDelay(3000);
        mRollPagerView.setVisibility(View.GONE);

        initBanner();


        timeGridView = (MyGridView) view.findViewById(R.id.time);
        adapter_time = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        timeGridView.setOnItemClickListener(this);
        timeGridView.setAdapter(adapter_time);

        sureButton = (Button) view.findViewById(R.id.sure_button);
        functionMyGridView = (MyGridView) view.findViewById(R.id.function);
        intentMyGridView = (MyGridView) view.findViewById(R.id.intent);
        otherMyGridView = (MyGridView) view.findViewById(R.id.other);
        mAppCompatEditText = (AppCompatEditText) view.findViewById(R.id.phone);
        if (GPJApplication.getInstance().isLogin()) {
            loginLinearLayout.setVisibility(View.GONE);
        } else {
            String phone = (String) SharedPreferencesUtil.get(mBuyCarVipActivity, "vip_phone", "");
            if (!TextUtils.isEmpty(phone)) {
                isPhoneNumRight = true;
                mAppCompatEditText.setText(phone);
            }
        }
        mVipLimitDialog = new VipLimitDialog(mBuyCarVipActivity);
        sureButton.setOnClickListener(this);
        intent_textview.setOnClickListener(this);
        adapter_function = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        adapter_intent = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        adapter_other = new CarlistSelectFilterAdapter(mBuyCarVipActivity);

        functionMyGridView.setAdapter(adapter_function);
        intentMyGridView.setAdapter(adapter_intent);
        otherMyGridView.setAdapter(adapter_other);

        functionMyGridView.setOnItemClickListener(this);
        intentMyGridView.setOnItemClickListener(this);
        otherMyGridView.setOnItemClickListener(this);

        mAppCompatEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = mAppCompatEditText.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    isPhoneNumRight = false;
                    setSureButton();
                    return;
                }
                if (phone.length() < 11 || !phone.startsWith("1")) {
                    isPhoneNumRight = false;
                    setSureButton();
                    return;
                }
                isPhoneNumRight = true;
                setSureButton();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        priceEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setSureButton();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        getSaveData();
        initGridView();
    }


    private void getSaveData() {
        if (mBuyCarVipActivity.vipBuyEntity == null) return;
        str_time = mBuyCarVipActivity.vipBuyEntity.getExpect_period();
        str_function = getStringFromList(mBuyCarVipActivity.vipBuyEntity.getUses());
        str_intent = getStringFromList(mBuyCarVipActivity.vipBuyEntity.getVehicle_model());
        str_others = getStringFromList(mBuyCarVipActivity.vipBuyEntity.getOther_recommend());
        str_price = mBuyCarVipActivity.vipBuyEntity.getPrice();
        if(!TextUtils.isEmpty(str_price)){
            priceEditText.setText(str_price);
        }
    }


    private String getStringFromList(List<String> s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.size(); i++) {
            if (i == s.size() - 1) {
                sb.append(s.get(i));
            } else {
                sb.append(s.get(i) + ",");
            }
        }
        return sb.toString();
    }


    //判断其它是否自定义
    private boolean isSameOthers(String other) {
        if (TextUtils.isEmpty(other)) return true;
        int size = need_other.length;
        for (int i = 0; i < size; i++) {
            if (other.equals(need_other[i])) {
                return true;
            }
        }
        return false;
    }


    private void initGridView() {
        List<String> times = null;
        int size = 0;
        if (!TextUtils.isEmpty(str_time)) {
            times = Arrays.asList(str_time.split(","));
            size = times.size();
        }
        list_time = new ArrayList<SelectBean>();
        for (int i = 0; i < show_time.length; i++) {
            SelectBean bean = new SelectBean(show_time[i], need_time[i], false);
            if (times != null && !times.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_time[i].equals(times.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_time.add(bean);
        }


        List<String> functions = null;
        if (!TextUtils.isEmpty(str_function)) {
            functions = Arrays.asList(str_function.split(","));
            size = functions.size();
        }
        list_function = new ArrayList<SelectBean>();
        for (int i = 0; i < show_function.length; i++) {
            SelectBean bean = new SelectBean(show_function[i], need_function[i], false);
            if (functions != null && !functions.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_function[i].equals(functions.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_function.add(bean);
        }


        ArrayList<String> intents = null;
        if (!TextUtils.isEmpty(str_intent)) {
            intents = new ArrayList<String>();
            Collections.addAll(intents, str_intent.split(","));
            if (intents.contains("small_car") && intents.contains("compact_car")) {
                intents.remove("small_car");
                intents.remove("compact_car");
                intents.add("small_car,compact_car");
            }
            size = intents.size();
        }

        list_intent = new ArrayList<SelectBean>();
        for (int i = 0; i < show_intent.length; i++) {
            SelectBean bean = new SelectBean(show_intent[i], need_intent[i], false);
            if (intents != null && !intents.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_intent[i].equals(intents.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_intent.add(bean);
        }


        List<String> others = null;
        if (!TextUtils.isEmpty(str_others)) {
            others = Arrays.asList(str_others.split(","));
            size = others.size();
        }
        list_other = new ArrayList<SelectBean>();
        for (int i = 0; i < show_other.length; i++) {
            SelectBean bean = new SelectBean(show_other[i], need_other[i], false);
            if (others != null && !others.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (i == show_other.length - 1 && !isSameOthers(others.get(j))) {
                        other_msg = others.get(j);
                        bean.setNeed_name(other_msg);
                        bean.setShow_name("已自定义");
                        bean.setCheack(true);
                    } else {
                        if (need_other[i].equals(others.get(j))) {
                            bean.setCheack(true);
                        }
                    }
                }
            }
            list_other.add(bean);
        }

        adapter_time.setData(list_time);
        adapter_function.setData(list_function);
        adapter_intent.setData(list_intent);
        adapter_other.setData(list_other);
        setSureButton();
    }


    @Override
    public void onClick(View v) {
        if (v == sureButton) {
            float price = Float.parseFloat(priceEditText.getText().toString());
            if (price < 5 && str_intent.contains("suv")) {
                mVipLimitDialog.show();
            } else if (price < 5 && str_intent.contains("super_car")) {
                mVipLimitDialog.show();
            } else if (price < 5 && str_intent.contains("luxury_car")) {
                mVipLimitDialog.show();
            } else if (price > 30 && str_intent.contains("mini_car")) {
                mVipLimitDialog.show();
            } else {
                getRecomendCar();
            }
        } else if (v == intent_textview) {
            mBuyCarVipActivity.goIntent();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == functionMyGridView) {
            //用途多选
            str_function = resetChecked(list_function, position);
            adapter_function.setData(list_function);
            setSureButton();
        } else if (parent == intentMyGridView) {
            //意向多选
            str_intent = resetChecked(list_intent, position);
            adapter_intent.setData(list_intent);
            setSureButton();
        } else if (parent == otherMyGridView) {
            if (position == list_other.size() - 1) {
                if (TextUtils.isEmpty(other_msg)) {
                    VipBuycarFilterPopupWindow vipBuycarFilterPopupWindow = new VipBuycarFilterPopupWindow(mBuyCarVipActivity);
                    vipBuycarFilterPopupWindow.showAtLocation(sureButton, Gravity.BOTTOM, 0, 0);
                    return;
                } else {
                    deleteOther();
                    adapter_other.setData(list_other);
                    return;
                }
            }

            //其它多选
            str_others = resetChecked(list_other, position);
            if (!TextUtils.isEmpty(other_msg)) {
                str_others = str_others + "," + other_msg;
            }
            adapter_other.setData(list_other);
        } else if (parent == timeGridView) {
            if (list_time.get(position).isCheack()) {
                resetRadio(list_time);
                str_time = "";
            } else {
                resetRadio(list_time);
                list_time.get(position).setCheack(true);
                str_time = list_time.get(position).getNeed_name();
            }
            adapter_time.setData(list_time);
            setSureButton();
        }
    }


    //重置单选 (设置为false)
    private void resetRadio(List<SelectBean> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheack(false);
        }
    }


    //重置多选
    private String resetChecked(List<SelectBean> list, int position) {
        SelectBean sb = list.get(position);
        boolean ischeck = sb.isCheack();
        sb.setCheack(!ischeck);
        List<String> checkedName = new ArrayList<String>();       //将为true的字段保存在当前集合
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheack()) {
                checkedName.add(list.get(i).getNeed_name());
            }
        }
        String str_name = setcomposing(checkedName);
        return str_name;
    }

    //拼接字符串
    private String setcomposing(List<String> checkedName) {
        String names = "";
        for (int i = 0; i < checkedName.size(); i++) {
            if (i == checkedName.size() - 1) {
                names += checkedName.get(i);
            } else {
                names += checkedName.get(i) + ",";
            }
        }
        return names;
    }


    //其它条件的回调
    public void otherNeed(String msg) {
        other_msg = msg;
        int size = list_other.size() - 1;
        list_other.get(size).setNeed_name(msg);
        list_other.get(size).setShow_name("已自定义");
        list_other.get(size).setCheack(true);
        adapter_other.setData(list_other);
        if (TextUtils.isEmpty(str_others)) {
            str_others = msg;
        } else {
            str_others = str_others + "," + msg;
        }
    }


    //删除额外条件
    private void deleteOther() {
        int size = list_other.size() - 1;
        list_other.get(size).setNeed_name("");
        list_other.get(size).setCheack(false);
        list_other.get(size).setShow_name("自定义");
        if (str_others.contains(other_msg + ",")) {
            str_others = str_others.replace(other_msg + ",", "");
        } else if (str_others.contains("," + other_msg)) {
            str_others = str_others.replace("," + other_msg, "");
        } else {
            str_others = str_others.replace(other_msg, "");
        }
        other_msg = "";
    }


    //判断确认按钮是否可点
    private void setSureButton() {
        str_price = priceEditText.getText().toString();
        Float p = 0f;
        if (!TextUtils.isEmpty(str_price)) {
            p = Float.parseFloat(str_price);
        }
        if (!TextUtils.isEmpty(str_price) && p > 0 && !TextUtils.isEmpty(str_time) && !TextUtils.isEmpty(str_function) && !TextUtils.isEmpty(str_intent)) {
            if (loginLinearLayout.getVisibility() == View.VISIBLE) {
                if (isPhoneNumRight) {
                    sureButton.setBackgroundResource(R.drawable.button_big_bg);
                    sureButton.setEnabled(true);
                    return;
                } else {
                    sureButton.setBackgroundResource(R.drawable.button_no_click);
                    sureButton.setEnabled(false);
                    return;
                }
            }
            sureButton.setBackgroundResource(R.drawable.button_big_bg);
            sureButton.setEnabled(true);
        } else {
            sureButton.setBackgroundResource(R.drawable.button_no_click);
            sureButton.setEnabled(false);
        }
    }


    //获取意向好车
    public void getRecomendCar() {
        String phone;
        if (!GPJApplication.getInstance().isLogin()) {
            phone = mAppCompatEditText.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                Toast.makeText(mBuyCarVipActivity, "请输入手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (phone.length() < 11 || !phone.startsWith("1")) {
                Toast.makeText(mBuyCarVipActivity, "手机号输出有误,请重新输入", Toast.LENGTH_SHORT).show();
                return;
            }
            SharedPreferencesUtil.put(mBuyCarVipActivity, "vip_phone", mAppCompatEditText.getText().toString());
        } else {
            UserManager mUserManager = new UserManager(mBuyCarVipActivity);
            mUserManager = mUserManager.LoadUserInfo();
            phone = mUserManager.getPhone();
        }
        str_price = priceEditText.getText().toString();
        mVipBuycarBean.setPrice(str_price);
        mVipBuycarBean.setFunction(str_function);
        mVipBuycarBean.setItent(str_intent);
        mVipBuycarBean.setTimes(str_time);
        mVipBuycarBean.setOthers(str_others);
        mVipBuycarBean.setPhone(phone);
        mVipBuycarBean.setType("ambiguous");
        Intent intent = new Intent(mBuyCarVipActivity, VipRecomendCarActivity.class);
        intent.putExtra("mVipBuycarBean", mVipBuycarBean);
        startActivity(intent);
        StepMonitor.getInstance().addMonitor(new Monitor("click" , "vipBuy_submit" ,System.currentTimeMillis() , 1f));
        mBuyCarVipActivity.finish();

    }
}
